import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import React from 'react'

// API日志接口
export interface ApiLog {
    id: string
    timestamp: Date
    method: string
    url: string
    status: number
    duration: number
    level: 'info' | 'warn' | 'error'
    request: any
    response: any
    error?: string
}

// 调试信息接口
export interface DebugInfo {
    environment: string
    apiBaseUrl: string
    useMockApi: boolean
    timestamp: string
    userAgent: string
    viewport: {
        width: number
        height: number
    }
    performance: {
        memory?: any
        timing?: any
    }
    [key: string]: any
}

// 开发工具状态接口
interface DevToolsState {
    // 基础状态
    isEnabled: boolean
    useMockApi: boolean
    mockDataMode: string

    // API日志
    apiLogs: ApiLog[]
    maxLogs: number

    // 调试信息
    debugInfo: DebugInfo

    // 操作方法
    toggleDevTools: () => void
    toggleMockApi: () => void
    setMockDataMode: (mode: string) => void

    // API日志管理
    addApiLog: (log: ApiLog) => void
    clearApiLogs: () => void
    exportLogs: () => void

    // 调试信息管理
    updateDebugInfo: (info: Partial<DebugInfo>) => void

    // 工具方法
    logApiCall: (method: string, url: string, options?: any) => Promise<any>
    logApiResponse: (logId: string, response: any, duration: number) => void
    logApiError: (logId: string, error: any, duration: number) => void
}

// 获取初始调试信息
const getInitialDebugInfo = (): DebugInfo => ({
    environment: process.env.NODE_ENV || 'development',
    apiBaseUrl: process.env.NEXT_PUBLIC_API_BASE_URL || '',
    useMockApi: process.env.NEXT_PUBLIC_USE_MOCK_API === 'true',
    timestamp: new Date().toISOString(),
    userAgent: typeof window !== 'undefined' ? window.navigator.userAgent : '',
    viewport: {
        width: typeof window !== 'undefined' ? window.innerWidth : 0,
        height: typeof window !== 'undefined' ? window.innerHeight : 0
    },
    performance: typeof window !== 'undefined' && 'performance' in window ? {
        memory: (window.performance as any).memory,
        timing: window.performance.timing
    } : {}
})

// 创建开发工具store
export const useDevToolsStore = create<DevToolsState>()(
    persist(
        (set, get) => ({
            // 初始状态
            isEnabled: process.env.NODE_ENV === 'development',
            useMockApi: process.env.NEXT_PUBLIC_USE_MOCK_API === 'true',
            mockDataMode: 'default',
            apiLogs: [],
            maxLogs: 100,
            debugInfo: getInitialDebugInfo(),

            // 基础操作
            toggleDevTools: () => {
                set((state) => ({ isEnabled: !state.isEnabled }))
            },

            toggleMockApi: () => {
                set((state) => {
                    const newUseMockApi = !state.useMockApi

                    // 更新环境变量（仅在客户端）
                    if (typeof window !== 'undefined') {
                        // 注意：这只是临时设置，页面刷新后会恢复
                        (window as any).__NEXT_PUBLIC_USE_MOCK_API = newUseMockApi.toString()

                        // 刷新API客户端
                        import('../lib/apiClientFactory').then(({ refreshApiClient }) => {
                            refreshApiClient()
                        })
                    }

                    return {
                        useMockApi: newUseMockApi,
                        debugInfo: {
                            ...state.debugInfo,
                            useMockApi: newUseMockApi,
                            timestamp: new Date().toISOString()
                        }
                    }
                })
            },

            setMockDataMode: (mode: string) => {
                set((state) => {
                    // 刷新API客户端以应用新的模拟数据模式
                    if (typeof window !== 'undefined') {
                        import('../lib/apiClientFactory').then(({ refreshApiClient }) => {
                            refreshApiClient()
                        })
                    }

                    return {
                        mockDataMode: mode,
                        debugInfo: {
                            ...state.debugInfo,
                            mockDataMode: mode,
                            timestamp: new Date().toISOString()
                        }
                    }
                })
            },

            // API日志管理
            addApiLog: (log: ApiLog) => {
                set((state) => {
                    const newLogs = [...state.apiLogs, log]

                    // 限制日志数量
                    if (newLogs.length > state.maxLogs) {
                        newLogs.splice(0, newLogs.length - state.maxLogs)
                    }

                    return { apiLogs: newLogs }
                })
            },

            clearApiLogs: () => {
                set({ apiLogs: [] })
            },

            exportLogs: () => {
                const { apiLogs } = get()
                const dataStr = JSON.stringify(apiLogs, null, 2)
                const dataBlob = new Blob([dataStr], { type: 'application/json' })

                if (typeof window !== 'undefined') {
                    const url = URL.createObjectURL(dataBlob)
                    const link = document.createElement('a')
                    link.href = url
                    link.download = `api-logs-${new Date().toISOString().split('T')[0]}.json`
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    URL.revokeObjectURL(url)
                }
            },

            // 调试信息管理
            updateDebugInfo: (info: Partial<DebugInfo>) => {
                set((state) => ({
                    debugInfo: {
                        ...state.debugInfo,
                        ...info,
                        timestamp: new Date().toISOString()
                    }
                }))
            },

            // API调用日志记录
            logApiCall: async (method: string, url: string, options: any = {}) => {
                const logId = `api_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
                const startTime = Date.now()

                // 记录请求开始
                const requestLog: ApiLog = {
                    id: logId,
                    timestamp: new Date(),
                    method: method.toUpperCase(),
                    url,
                    status: 0, // 待更新
                    duration: 0, // 待更新
                    level: 'info',
                    request: {
                        headers: options.headers || {},
                        body: options.body,
                        params: options.params
                    },
                    response: null // 待更新
                }

                get().addApiLog(requestLog)

                return {
                    logId,
                    startTime,
                    updateResponse: (response: any, status: number) => {
                        get().logApiResponse(logId, response, Date.now() - startTime)
                    },
                    updateError: (error: any) => {
                        get().logApiError(logId, error, Date.now() - startTime)
                    }
                }
            },

            logApiResponse: (logId: string, response: any, duration: number) => {
                set((state) => ({
                    apiLogs: state.apiLogs.map(log =>
                        log.id === logId
                            ? {
                                ...log,
                                status: response.status || 200,
                                duration,
                                response: response.data || response,
                                level: response.status >= 400 ? 'error' : 'info'
                            }
                            : log
                    )
                }))
            },

            logApiError: (logId: string, error: any, duration: number) => {
                set((state) => ({
                    apiLogs: state.apiLogs.map(log =>
                        log.id === logId
                            ? {
                                ...log,
                                status: error.response?.status || 500,
                                duration,
                                level: 'error',
                                error: error.message || 'Unknown error',
                                response: error.response?.data || null
                            }
                            : log
                    )
                }))
            }
        }),
        {
            name: 'dev-tools-storage',
            partialize: (state) => ({
                isEnabled: state.isEnabled,
                useMockApi: state.useMockApi,
                mockDataMode: state.mockDataMode,
                // 不持久化日志和调试信息，避免存储过大
            })
        }
    )
)

// 开发工具钩子函数
export const useDevTools = () => {
    const store = useDevToolsStore()

    // 自动更新调试信息
    React.useEffect(() => {
        const updateViewport = () => {
            store.updateDebugInfo({
                viewport: {
                    width: window.innerWidth,
                    height: window.innerHeight
                }
            })
        }

        if (typeof window !== 'undefined') {
            window.addEventListener('resize', updateViewport)
            return () => window.removeEventListener('resize', updateViewport)
        }
    }, [store])

    return store
}

// API拦截器工具
export const createApiInterceptor = () => {
    const { logApiCall } = useDevToolsStore.getState()

    return {
        request: async (config: any) => {
            if (process.env.NODE_ENV === 'development') {
                const logger = await logApiCall(
                    config.method || 'GET',
                    config.url || '',
                    config
                )

                // 将logger附加到config中，以便在响应中使用
                config._logger = logger
            }

            return config
        },

        response: (response: any) => {
            if (process.env.NODE_ENV === 'development' && response.config._logger) {
                response.config._logger.updateResponse(response, response.status)
            }

            return response
        },

        error: (error: any) => {
            if (process.env.NODE_ENV === 'development' && error.config?._logger) {
                error.config._logger.updateError(error)
            }

            return Promise.reject(error)
        }
    }
}

export default useDevToolsStore